#!/usr/bin/python2.6

"""Datastore for BGG game collection data
"""

import csv
import re

class GameStore:
  def __init__(self):
    self.Clear()

  def Clear(self):
    "Clears the loaded data"
    self.data_ = []
  
  def LoadFromFile(self, filename):
    "Loads data from a bgg datafile"

    def Listify(datadict, field):
      "Converts the named field to a list of numbers from csv"
      value = datadict(field)
      if not value:
        value = []
      else:
        value = map(int(value.split(",")))
      
    file = open(filename, "r")
    csv_reader = csv.reader(file)

    headings = None
    for row in csv_reader:
      if not headings:
        headings = row
        next


      game_object = dict(zip(headings, row))
      # process fields that need some work.

      Listify(game_oject, "bggrecplayers")
      
      Listify(game_oject, "bggbestplayers")
      
      self.data_.append(game_object)


  def FilterIterator(self, filterfn):
    """"Hands back just the objects that filterfn triggers on.

    Arguments:
      filterfn either a single filter function or a list of filter
         functions which are checked against each item"""
    for item in self.data_:
      if type(filterfn) is not list:
        if filterfn(item):
          yield item
      else:
        matches = True
        for filter in filterfn:
          if not filterfn(item):
            matches = False
            break
        if matches:
          yield item
          
        
